const mongoose = require('mongoose');
const GameUserModel = mongoose.models['GameUser'];
const ChannelModel = mongoose.models['Channel'];
const CensusModel = mongoose.models['Census'];
const ChannelCensusModel = mongoose.models['ChannelCensus'];
const Cron = require('node-cron');
const config=require('./config');
let clickCensus = require('./db/model/admin.clickCensus');
module.exports={
    async run(){
        // 每小时统计
        Cron.schedule('0 0 * * * *', async function(){
            await this.censusRegisterGameUser();
        }.bind(this));
        // 每日统计
        Cron.schedule('2 0 0 * * *', async function(){
            await this.censusDayRegisterGameUser();
        }.bind(this));
        // 每日凌晨4点任务
        Cron.schedule('0 1 0 * * *', async function(){
            await this.censusAll();
        }.bind(this));
        // Cron.schedule('0 * * * * *', async function(){
        // }.bind(this));
        Cron.schedule('0 1 1 * * *', async function(){
            await this.copyPrice();
        }.bind(this));
    },
    async copyPrice(){
        let addDate = new Date(Date.now() - 24 * 60 * 60 * 1000).toLocaleDateString();
        await clickCensus.checkData(addDate);
    },
    //统计注册人数，根据appId来源统计
    async censusRegisterGameUser(){
        let now=new Date().getTime();
        let minTimeTick=now-3600000;
        let gameUsers=await GameUserModel.find({registerTimeTick:{$gte:minTimeTick}});
        let channels=await ChannelModel.find({});
        for(let i=0;i<channels.length;i++){
            let channelId=channels[i]._id.toString();
            let census={group:'渠道统计',type:channelId,count:0,timeTick:now};
            for(let j=0;j<gameUsers.length;j++){
                if(gameUsers[j].referrerInfoAppId==channelId){
                    census.count++;
                }
            }
            if(census.count>2&&channels[i].allCount >= channels[i].startCount){
                census.count = Math.ceil(census.count * channels[i].percent / 100);
            }
            channels[i].allCount+=census.count;
            await channels[i].save();
            await CensusModel.create(census);
        }
        await CensusModel.create({group:'渠道统计',type:'ALL',count:gameUsers.length,timeTick:now});
    },
    //统计1小时内进行过游戏的玩家数量
    async censusPlayGameUser(){
        let now=new Date().getTime();
        let maxTimeTick=now-3600000;
        let minTimeTick=now-7200000;
        let gameUsers=await GameUserModel.find({registerTimeTick:{$gte:minTimeTick,$lt:maxTimeTick},'ppt.isPlayGame':true});
        let channels=await ChannelModel.find({});
        for(let i=0;i<channels.length;i++){
            let channelId=channels[i]._id.toString();
            let census={group:'渠道玩过的统计',type:channelId,count:0,timeTick:now};
            for(let j=0;j<gameUsers.length;j++){
                if(gameUsers[j].referrerInfoAppId==channelId){
                    census.count++;
                }
            }
            await CensusModel.create(census);
        }
        await CensusModel.create({group:'渠道玩过的统计',type:'ALL',count:gameUsers.length,timeTick:now});
    },
    //生成头一天所有该统计的数据，有次日留存，三日留存，
    async censusAll(){
        let ChannelEventModel=mongoose.models['ChannelEvent'];
        //如果没有数据，则先生成初始数据
        let addDate=new Date(new Date().getTime()-(24*3600000)).toLocaleDateString(); //获取头一天是哪天
        let channels=await ChannelModel.find({});
        let endTimeTick=new Date(addDate+' 23:59:59').getTime()+999;
        for(let i=0;i<channels.length;i++){
            let channelId=channels[i]._id.toString();
            let channelCensus=await ChannelCensusModel.findOne({addDate:addDate,channelId:channelId});
            if(!channelCensus){
                channelCensus=await ChannelCensusModel.create({
                    addDate:addDate,
                    channelId:channels[i]._id.toString(),
                    channelName:channels[i].name
                })
            }
            // 去重日跳转用户总数
            channelCensus.navigateUserCount = await GameUserModel.countDocuments({referrerInfoAppId:channelId,lastLoginTick:{$gt:endTimeTick-86400000,$lte:endTimeTick}});
            //生成真实注册用户数据
            channelCensus.registerUserCount=await GameUserModel.countDocuments({referrerInfoAppId:channelId,registerTimeTick:{$gte:endTimeTick-86400000,$lt:endTimeTick}});
            //生成次日留存数据
            channelCensus.nextDayCount=await GameUserModel.countDocuments({referrerInfoAppId:channelId,lastLoginTick:{$gte:endTimeTick-86400000,$lt:endTimeTick},registerTimeTick:{$gte:endTimeTick-(86400000*2),$lt:endTimeTick-86400000}});
            channelCensus.threeDayCount=await GameUserModel.countDocuments({referrerInfoAppId:channelId,lastLoginTick:{$gte:endTimeTick-86400000,$lt:endTimeTick},registerTimeTick:{$gte:endTimeTick-(86400000*4),$lt:endTimeTick-(86400000*3)}});;
            //生成其他事件相关数据
            channelCensus.openCount=await ChannelEventModel.countDocuments({channelId:channelId,addTimeTick:{$lte:endTimeTick},eventName:'打开友情链接'});
            channelCensus.newUserOpenCount=await ChannelEventModel.countDocuments({channelId:channelId,addTimeTick:{$lte:endTimeTick},eventName:'新用户打开友情链接'});
            channelCensus.videoCount=await ChannelEventModel.countDocuments({channelId:channelId,addTimeTick:{$lte:endTimeTick},eventName:'观看视频成功'});
            channelCensus.newUserVideoCount=await ChannelEventModel.countDocuments({channelId:channelId,addTimeTick:{$lte:endTimeTick},eventName:'新用户观看视频成功'});
            channelCensus.percent = channels[i].percent;
            await channelCensus.save();
        }
        await ChannelEventModel.remove({addTimeTick:{$lte:endTimeTick}});
    },
    //统计每日授权总计
    async censusDayRegisterGameUser(){
        let now=new Date().getTime();
        let gteTime=now-24*3600000+500;
        let ltTime=now+500;
        let channels=await ChannelModel.find({});
        for(let i=0;i<channels.length;i++){
            let cencuses=await CensusModel.find({group:'渠道统计',type:channels[i]._id.toString(),timeTick:{$gte:gteTime,$lt:ltTime}});
            let census={group:'渠道日统计',type:channels[i]._id.toString(),count:0,timeTick:now};
            for(let j=0;j<cencuses.length;j++){
                census.count+=cencuses[j].count;
            }
            await CensusModel.create(census);
        }
        let allCencuses=await CensusModel.find({group:'渠道统计',type:'ALL',timeTick:{$gte:gteTime,$lt:ltTime}});
        let allCencus={group:'渠道日统计',type:'ALL',count:0,timeTick:now};
        for(let j=0;j<allCencuses.length;j++){
            allCencus.count+=allCencuses[j].count;
        }
        await CensusModel.create(allCencus);
    },
    //统计友情链接点击数量，按小时统计
    async censusFriendLinkClick(){
        let now=new Date().getTime();
        let clickEvents=await ClickEventModel.find({group:'友情链接点击统计',timeTick:{$lte:now}});
        let friendlyLinks=await FriendlyLinkModel.find({});
        for(let i=0;i<friendlyLinks.length;i++){
            let filterClickEvent=clickEvents.filter(item=>{return item.data.sceneName==friendlyLinks[i].sceneName&&item.data.area==friendlyLinks[i].area&&item.data.appId==friendlyLinks[i].appId;});
            await CensusModel.create({group:'友情链接点击统计',type:`${friendlyLinks[i].sceneName}_${friendlyLinks[i].area}_${friendlyLinks[i].appId}`,count:filterClickEvent.length,timeTick:now});
        }
        await CensusModel.create({group:'友情链接点击统计',type:'ALL',count:clickEvents.length,timeTick:now});
        for(let i=0;i<clickEvents.length;i++){
            await clickEvents[i].remove();
        }
    },
    //统计友情链接点击数量，去除重复
    async censusFriendLinkClickDistinct(){
        let now=new Date().getTime();
        let clickEvents=await ClickEventModel.find({group:'友情链接点击去重统计',timeTick:{$lte:now}});
        let friendlyLinks=await FriendlyLinkModel.find({});
        for(let i=0;i<friendlyLinks.length;i++){
            let filterClickEvent=clickEvents.filter(item=>{return item.data.sceneName==friendlyLinks[i].sceneName&&item.data.area==friendlyLinks[i].area&&item.data.appId==friendlyLinks[i].appId;});
            await CensusModel.create({group:'友情链接点击去重统计',type:`${friendlyLinks[i].sceneName}_${friendlyLinks[i].area}_${friendlyLinks[i].appId}`,count:filterClickEvent.length,timeTick:now});
        }
        await CensusModel.create({group:'友情链接点击去重统计',type:'ALL',count:clickEvents.length,timeTick:now});
        for(let i=0;i<clickEvents.length;i++){
            await clickEvents[i].remove();
        }
    },

    //定时删除上传的录音文件
    deleteUpload(){
        if(!config.debug){
            let fs=require('fs');
            console.log('定时删除文件任务运行:' + new Date());
            let fileUrl='./public/upload/mp3';
            let files = fs.readdirSync(fileUrl);//读取该文件夹
            let now=new Date().getTime();
            files.forEach(function(file){
                var stats = fs.statSync(fileUrl+'/'+file);
                if(now-stats.atime.getTime()>60000){
                    fs.unlinkSync(fileUrl+'/'+file);
                    // console.log("定时删除文件"+fileUrl+'/'+file+"成功");
                }
            });
        }
    }
};